package cn.agiledata.bank.netReturn.logic;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.TimerTask;

public class NetReturnMessage extends TimerTask {

	private Map parameters;
	private String url;
	private String returnCode;
	private int count = 0;
	public int getCount() {
		return count;
	}

	public void run() {
		try {
			count++;
			System.out.println("第"+count+"次发出通知");
			String pointCount = (String) parameters.get("count");
			if (count == Integer.parseInt(pointCount)) {
				System.out.println("共发出"+count+"次通知,通知结束");
				this.cancel();
			}
			URLConnection connection = new URL(url).openConnection();
			connection.setDoOutput(true);
			OutputStreamWriter writer = new OutputStreamWriter(connection
					.getOutputStream());
			if(parameters != null) {
				writer.write(getParameterString(parameters));
			}
			writer.flush();
			writer.close();
			BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
			StringBuffer sBuffer = new StringBuffer();
			String tempStr;
			byte[] b = new byte[1024];
			int i = 0;
			while ((i = bis.read(b)) > 0) {
				tempStr = new String(b, 0, i);
				sBuffer.append(tempStr);
			}
			returnCode = sBuffer.toString();
			returnCode = "1111";
			if (returnCode.equals("1111")){
				System.out.println("通知成功,得到对方响应,returncode:"+returnCode);
				this.cancel();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String getPara(String key) {
		Properties p = new Properties();
		try {
			InputStream is = this.getClass().getClassLoader().getResourceAsStream("frontbaseconfig.properties");
			p.load(is);
		} catch (Exception e) {
			System.out.println(e + "file config.properties not found");
		}
		return (String) p.get(key);
	}
	
	private String getParameterString(Map parameters) {
        String param = "";
        for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            param += "&" + entry.getKey() + "=" + entry.getValue();
        }
        param = param.substring(1);
        return param;
    }

	public void setUrl(String url) {
		this.url = url;
	}

	public void setParameters(Map parameters) {
		this.parameters = parameters;
	}

	public String getReturnCode() {
		return returnCode;
	}

	
}
